<template>
  <div class="page article-details-wrapper">
    <ArticleDetailsLayout>
      <template #content>
        <el-card class="box-card">
          <ArticleDetails v-bind="article" ref="detailsEl"></ArticleDetails>
          <el-divider></el-divider>
          <RewardBar></RewardBar>
        </el-card>
        <CommentsCard class="comment-card"></CommentsCard>
      </template>
      <template #sidebar>
        <div class="sidebar-wrapper">
          <AuthorCard :nickname="author.nickname" :avatar="author.avatarUrl" :signature="author.signature"></AuthorCard>
          <DirectoryCard v-if="titles[0]" :titles="titles" @anchor="handleClickAnchor" />
          <ArticleRankCard title="Ta的热门文章" :rank="hotArticle" :show-read-count="false" @item="handleClickRankItem" />
        </div>
      </template>
    </ArticleDetailsLayout>
  </div>
</template>

<script>
import ArticleDetailsLayout from './layout.vue'
import ArticleDetails from './components/ArticleDetails.vue'
import AuthorCard from './components/AuthorCard.vue'
import RewardBar from './components/RewardBar.vue'
import DirectoryCard from './components/DirectoryCard.vue'
import ArticleRankCard from '@/components/ArticleRankCard.vue'
import CommentsCard from './components/CommentsCard.vue'
import api from '@/api'
export default {
  name: 'ArticleDetailsView',
  components: {
    ArticleDetailsLayout,
    ArticleDetails,
    AuthorCard,
    RewardBar,
    DirectoryCard,
    ArticleRankCard,
    CommentsCard
  },
  props: {
    id: {
      type: String
    }
  },
  data() {
    return {
      article: {
        _id: '',
        author_id: '',
        title: '',
        desc: '',
        coverUrl: '',
        content: '',
        star: 0,      //点赞
        favorite: 0,  //收藏
        readCount: 0,
        publish: false,
        createDate: '',
        publishDate: '',
        lastEditDate: '',
        tags: [],
        // category: {},
      },
      hotArticle: [],  //作者的热门文章
      author: {},
      titles: []      //文章标题
    }
  },
  async mounted() {
    console.log('mounted id:', this.id)
    await this.loadArticle(this.id)
    this.initDirectory()
    await this.loadAuthor()
    await this.loadHotArticle()
  },
  beforeRouteEnter() {
    // 解决页面显示时不在顶部的问题
    document.body.scrollTop = 0
    document.documentElement.scrollTop = 0
    // 兼容IE
    window.scrollTo(0, 0)
  },
  async beforeRouteUpdate() {
  },
  methods: {
    async loadArticle(id) {
      console.log('this.id', id)
      if (!id) { return }
      const result = await api.article.getById(id)
      Object.keys(this.article).forEach(key => {
        this.article[key] = result.data.article[key]
      })
      console.log('article:', this.article)
    },
    async loadAuthor() {
      if (!this.article.author_id) { return }
      const result = await api.user.getProfileById(this.article.author_id)
      this.author = result.data.user
    },
    async loadHotArticle() {
      const result = await api.article.getHot(this.author._id)
      this.hotArticle = result.data.articles
    },
    initDirectory() {
      // 初始化目录
      const anchors = this.$refs.detailsEl.preview.$el.querySelectorAll('h1,h2,h3,h4,h5,h6')
      const titles = Array.from(anchors).filter((title) => !!title.innerText.trim())

      if (titles.length === 0) {
        this.titles = []
        return
      }

      const hTags = Array.from(new Set(titles.map((title) => title.tagName))).sort()

      this.titles = titles.map((el) => ({
        title: el.innerText,
        lineIndex: el.getAttribute('data-v-md-line'),
        indent: hTags.indexOf(el.tagName),            //缩进等级
      }))
    },
    handleClickAnchor(anchor) {
      // 文章目录导航从
      const preview = this.$refs.detailsEl.preview
      const { lineIndex } = anchor

      const heading = preview.$el.querySelector(`[data-v-md-line="${lineIndex}"]`)

      if (heading) {
        preview.scrollToTarget({
          target: heading,
          scrollContainer: window,
          top: 60,
        })
      }
    },
    async handleClickRankItem(index) {
      const articleId = this.hotArticle[index]._id
      await this.loadArticle(articleId)
      this.initDirectory()
    }
  }
}
</script>

<style lang="scss" scoped>
.sidebar-wrapper {
  &>.el-card {
    margin-bottom: 18px;
  }
}

.comment-card {
  margin-top: 18px;
}
</style>
